<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <span>系统设置</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="140px"
        class="settings-form"
        v-loading="loading"
      >
        <!-- 基本设置 -->
        <div class="settings-section">
          <h2>基本设置</h2>
          <el-form-item label="网站名称" prop="siteName">
            <el-input v-model="formData.siteName" placeholder="请输入网站名称" />
          </el-form-item>

          <el-form-item label="网站LOGO" prop="logo">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleLogoSuccess"
              :before-upload="beforeLogoUpload"
              name="image"
            >
              <img v-if="formData.logo" :src="formData.logo" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="formData.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>

          <el-form-item label="客服微信" prop="serviceWechat">
            <el-input v-model="formData.serviceWechat" placeholder="请输入客服微信" />
          </el-form-item>
        </div>

        <!-- 交易设置 -->
        <div class="settings-section">
          <h2>交易设置</h2>
          <el-form-item label="自动确认收货时间" prop="autoConfirmDays">
            <el-input-number 
              v-model="formData.autoConfirmDays" 
              :min="1" 
              :max="30"
            />
            <span class="unit-text">天</span>
          </el-form-item>

          <el-form-item label="自动关闭订单时间" prop="autoCloseDuration">
            <el-input-number 
              v-model="formData.autoCloseDuration" 
              :min="1" 
              :max="1440"
            />
            <span class="unit-text">分钟</span>
          </el-form-item>

          <el-form-item label="支付方式" prop="paymentMethods">
            <el-checkbox v-model="formData.enableWechatPay">微信支付</el-checkbox>
          </el-form-item>
        </div>

        <!-- 管理员账号 -->
        <div class="settings-section">
          <h2>管理员账号</h2>
          <div class="admin-header">
            <el-button type="primary" @click="handleAddAdmin">添加管理员</el-button>
          </div>
          <el-table :data="formData.adminList" style="width: 100%">
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="role" label="角色">
              <template #default="scope">
                {{ scope.row.role === 'superadmin' ? '超级管理员' : '普通管理员' }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                  {{ scope.row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button link type="primary" @click="handleEditAdmin(scope.row)">编辑</el-button>
                <el-button 
                  link 
                  type="danger" 
                  @click="handleDeleteAdmin(scope.row)"
                  :disabled="scope.row.role === 'superadmin'"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">保存设置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 管理员编辑对话框 -->
    <el-dialog
      v-model="adminDialogVisible"
      :title="editingAdmin ? '编辑管理员' : '添加管理员'"
      width="500px"
    >
      <el-form
        ref="adminFormRef"
        :model="adminForm"
        :rules="adminRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="adminForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingAdmin">
          <el-input v-model="adminForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="adminForm.role" placeholder="请选择角色">
            <el-option label="超级管理员" value="superadmin" />
            <el-option label="普通管理员" value="admin" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="adminForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adminDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveAdmin">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { 
  getSettings, 
  updateSettings, 
  getAdminList,
  addAdmin,
  updateAdmin,
  deleteAdmin
} from '@/api/settings'

const formRef = ref(null)
const adminFormRef = ref(null)
const loading = ref(false)
const submitting = ref(false)
const adminDialogVisible = ref(false)
const editingAdmin = ref(null)
const uploadUrl = import.meta.env.VITE_API_URL + '/api/upload/simple'

// 表单数据
const formData = reactive({
  siteName: '',
  logo: '',
  contactPhone: '',
  serviceWechat: '',
  autoConfirmDays: 7,
  autoCloseDuration: 30,
  enableWechatPay: true,
  adminList: []
})

// 管理员表单
const adminForm = reactive({
  username: '',
  password: '',
  role: '',
  status: 1
})

// 表单验证规则
const rules = {
  siteName: [
    { required: true, message: '请输入网站名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  contactPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

const adminRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 获取设置数据
const fetchSettings = async () => {
  loading.value = true
  try {
    const { data } = await getSettings()
    Object.assign(formData, data)
    // 获取管理员列表
    const adminRes = await getAdminList()
    formData.adminList = adminRes.data.list
  } catch (error) {
    ElMessage.error('获取设置数据失败')
  } finally {
    loading.value = false
  }
}

// Logo上传相关方法
const handleLogoSuccess = (res) => {
  formData.logo = res.url
}

const beforeLogoUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

// 管理员相关方法
const handleAddAdmin = () => {
  editingAdmin.value = null
  Object.assign(adminForm, {
    username: '',
    password: '',
    role: '',
    status: 1
  })
  adminDialogVisible.value = true
}

const handleEditAdmin = (row) => {
  editingAdmin.value = row
  Object.assign(adminForm, {
    ...row,
    password: '' // 编辑时不显示密码
  })
  adminDialogVisible.value = true
}

const handleDeleteAdmin = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该管理员吗？', '提示', {
      type: 'warning'
    })
    await deleteAdmin(row.id)
    ElMessage.success('删除成功')
    fetchSettings() // 重新获取列表
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSaveAdmin = async () => {
  if (!adminFormRef.value) return
  
  await adminFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (editingAdmin.value) {
          await updateAdmin(editingAdmin.value.id, adminForm)
        } else {
          await addAdmin(adminForm)
        }
        adminDialogVisible.value = false
        ElMessage.success('保存成功')
        fetchSettings() // 重新获取列表
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        const submitData = {
          siteName: formData.siteName,
          logo: formData.logo,
          contactPhone: formData.contactPhone,
          serviceWechat: formData.serviceWechat,
          autoConfirmDays: formData.autoConfirmDays,
          autoCloseDuration: formData.autoCloseDuration,
          enableWechatPay: formData.enableWechatPay
        }
        await updateSettings(submitData)
        ElMessage.success('保存成功')
      } catch (error) {
        ElMessage.error('保存失败')
      } finally {
        submitting.value = false
      }
    }
  })
}

onMounted(() => {
  fetchSettings()
})
</script>

<style scoped>
.settings-container {
  padding: 20px;
}

.settings-card {
  max-width: 1000px;
  margin: 0 auto;
}

.settings-section {
  margin-bottom: 30px;
  border-bottom: 1px solid #eee;
  padding-bottom: 20px;
}

.settings-section h2 {
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.admin-header {
  margin-bottom: 20px;
}

.unit-text {
  margin-left: 10px;
  color: #666;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style> 